import { createSlice, createAsyncThunk } from "@reduxjs/toolkit";
import type { AsyncThunk, ActionReducerMapBuilder, PayloadAction, Slice } from '@reduxjs/toolkit'
import { getTimeExport, type getTimeExportParams } from './totalDateExportAPI'
import dayjs from "dayjs";
import { TZ } from "@/utils/env";

const threeDaysAgoStart = dayjs().tz(TZ).subtract(3, 'day').unix();
const todayEnd = dayjs().tz(TZ).unix();

interface InitialState {
  params: getTimeExportParams,
  table: {
    status: 'init' | 'loading' | 'success' | 'error',
    data: Res | undefined,
    params?: getTimeExportParams
  }
}

const initialState: InitialState = {
  params: {
    start_time: threeDaysAgoStart,
    end_time: todayEnd,
    download_type: '',
    re_statistic: 0,
  },
  table: {
    status: "init",
    data: undefined,
  }
};

type Res = {
  data: {
    path:string
  }
}
type AsyncRes = {
  data: Res,
  params: getTimeExportParams
}
export const getTimeExportAsync: AsyncThunk<AsyncRes, getTimeExportParams, {}> = createAsyncThunk<AsyncRes, getTimeExportParams, {}>(
  "timeExport/getTimeExportAsync",
  async (params) => {
    const res: Res = await getTimeExport(params);
    return {
      data: res,
      params
    };
  }
);
const tableStatus: (builder: ActionReducerMapBuilder<InitialState>) => void = (builder: ActionReducerMapBuilder<InitialState>): void => {
  builder
    .addCase(getTimeExportAsync.pending, (state: InitialState): void => {
      state.table.status = "loading";
    })
    .addCase(getTimeExportAsync.fulfilled, (state: InitialState, action: PayloadAction<AsyncRes>): void => {
      state.table.status = "success";
      state.table.data = action.payload.data;
      state.table.params = action.payload.params
    })
    .addCase(getTimeExportAsync.rejected, (state: InitialState): void => {
      state.table.status = "error";
    });
};

type Reducers = {
  changeParams: (state: InitialState, action: PayloadAction<Partial<getTimeExportParams>>) => void
}
type Selectors = {}
const userExportSlice: Slice<InitialState, Reducers, 'timeExport', 'timeExport', Selectors> = createSlice<InitialState, Reducers, 'timeExport', Selectors, 'timeExport'>({
  name: "timeExport",
  initialState,
  reducers: {
    changeParams(state: InitialState, action: PayloadAction<Partial<getTimeExportParams>>): void {
      state.params = {
        ...state.params,
        ...action.payload,
      };
    }
  },
  extraReducers(builder: ActionReducerMapBuilder<InitialState>): void {
    tableStatus(builder);
  },
});

export const { changeParams }: typeof userExportSlice.actions = userExportSlice.actions;

export default userExportSlice.reducer;
